'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'

export default function LoginPage() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const router = useRouter()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError('')
    
    console.log('开始登录请求...')
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      })
      
      console.log('登录响应:', res)
      const data = await res.json()
      console.log('响应数据:', data)
      
      if (res.ok) {
        console.log('登录成功，准备跳转...')
        window.dispatchEvent(new Event('auth-change'))
        try {
          setTimeout(async () => {
            window.location.href = '/users'
          }, 500)
        } catch (routerError) {
          console.error('路由跳转失败:', routerError)
        }
      } else {
        console.log('登录失败:', data.error)
        setError(data.error || '登录失败')
      }
    } catch (err) {
      console.error('登录错误:', err)
      setError('登录失败，请重试')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="max-w-md mx-auto p-6">
      <form 
        onSubmit={handleSubmit} 
        className="space-y-4 bg-white p-8 rounded-lg shadow-md"
      >
        <h1 className="text-2xl font-bold text-center mb-6 text-[#1e3a8a]">登录</h1>
        {error && (
          <div className="bg-red-50 text-red-500 p-3 rounded">
            {error}
          </div>
        )}
        <div>
          <label className="block mb-1 text-gray-700">邮箱</label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full p-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            required
          />
        </div>
        <div>
          <label className="block mb-1 text-gray-700">密码</label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full p-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            required
          />
        </div>
        <button
          type="submit"
          disabled={isLoading}
          className="w-full p-2 bg-[#1e3a8a] text-white rounded hover:bg-[#1e3a8a]/90 transition-colors disabled:opacity-50"
        >
          {isLoading ? '登录中...' : '登录'}
        </button>
      </form>
    </div>
  )
} 